package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    DictMapper dictMapper;
    @Override
//    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> haveChilsData(Long id) {
        String sql="select * from dict where parent_id =id";
        //查出首层得子节点
        QueryWrapper<Dict> queryWrapper=new QueryWrapper();
        queryWrapper.eq("parent_id",id);
        List<Dict> list = baseMapper.selectList(queryWrapper);
        //遍历每个查出得节点，添加是否还有下一层得子节点
        log.info("是否查到数据{}",list);
        for (Dict dict:list){
            Long id1 = dict.getId();
            boolean haveNode = this.isHaveNode(id1);
            dict.setHasChildren(haveNode);
        }
        return list;
    }
     //导出数据
    @Override
    public void exportDataServuce(HttpServletResponse httpResponse) {
        //设置请求头
        httpResponse.setContentType("application/vnd.ms-excel");  //指定下载得格式
        httpResponse.setCharacterEncoding("utf-8");
        String fileName = "dict";
        //Content-disposition:Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。当Internet Explorer接收到头时，他会激活文件下载对话框，它的文件名框自动填充headers指定的文件名。
        httpResponse.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //查询数据
        List<Dict> dictList = baseMapper.selectList(null);
        //把查询得数据所需得字段遍历集合中
        ArrayList<DictEeVo> dictEeVos = new ArrayList<>();
        for (Dict dict : dictList){
            //Dict->DictEeVo
//            Dict dict = new Dict();
            DictEeVo dictVo = new DictEeVo();
//            Long id = dict.getId();
//            dictVo.setId(id);
            BeanUtils.copyProperties(dict, dictVo, DictEeVo.class);
            dictEeVos.add(dictVo);
        }
        try {
            EasyExcel.write(httpResponse.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictEeVos);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
//    @CacheEvict(value = "dict", allEntries=true)
    public void importExceData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        log.info("{}",parentDictCode);
        //如果value能唯一定位数据字典，parentDictCode可以传空，例如：省市区的value值能够唯一确定
        if(StringUtils.isEmpty(parentDictCode)){
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            log.info("查看字典是否为null{}",dict);
                return dict.getName();
        }else {
            //获取到Dict
            Dict parentDict = this.getByDictsCode(parentDictCode);
            log.info("对象是{}",parentDict);
            Long parent_id = parentDict.getId();

            //通过parentDict获取id和value
            Dict dict = dictMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id",parent_id)
                    .eq("value", value));
                return dict.getName();
        }

    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode 获取id
        Dict nextDict = this.getByDictsCode(dictCode);
        //id获取下一节点
        List<Dict> dictList = this.haveChilsData(nextDict.getId());
        return dictList;

    }

    //根据parentDictCode查询Dict
    private Dict getByDictsCode(String dictCode){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict parentDict = baseMapper.selectOne(wrapper);
        return parentDict;
    }
    //判断节点下有无节点
    public boolean isHaveNode(Long id){
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id",id);
        //查询节点得个数
        Integer integer = baseMapper.selectCount(dictQueryWrapper);
        return integer>0;
    }

}
